let timeUtils = require('./timeUtils')

let getFromYun = async function (account,
  selectLib) {
  let count = await wx.cloud.database().collection("testRecords").where({
    account,
    selectLib
  }).orderBy('time', 'desc').count()
  let total = count.total
  //计算需分几次取
  let batchTimes = Math.ceil(total / MAX_LIMIT)
  let tasks = []
  for (let i = 0; i < batchTimes; i++) { //由于数据长度限制，需要不停从数据库拿取数据
    let promise = await wx.cloud.callFunction({
      name: "getRecords",
      data: {
        account,
        selectLib,
        i,
        MAX_LIMIT
      }
    }).then()
    tasks.push(promise)
  }
  let res = {
    data: []
  }
  if (tasks.length > 0) { //说明没查到数据，说明用户没有收藏过题目
    res = await Promise.all(tasks)
    let data = new Array()
    for (let a = 0; a < res.length; a++) {
      let e = res[a]
      for (let b = 0; b < e.result.data.length; b++) {
        data.push(e.result.data[b])
      }
    }
    return data
  }
  return tasks
}

let getRecord = async function name(account,
  selectLib, i,
  MAX_LIMIT) {
  //不停从数据库拿数据，实现分页查询

  let res = await wx.cloud.database().collection("testRecords").where({
    account,
    selectLib
  }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).orderBy('time', 'desc').get()
  let title = res.data
  let response = new Array()
  //从title中提取考试时间，考试得分和_id
  for (let i = 0; i < title.length; i++) {
    let element = title[i];
    let {
      _id,
      score,
      time
    } = element
    time = await timeUtils.timeFormat(time)
    let data = {
      _id,
      score,
      time
    }
    response.push(data)
  }
  return response
}
module.exports = {
  getFromYun,
  getRecord
}